#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
from datetime import datetime

from conn.MyLogs import MyLogs
from members.beans.MemberWieghtObj import MemberWieghtObj


class MemeberWeightService:
    std_array = {}
    conn = None

    def __init__(self, conn):
        self.conn = conn

    def fetch(self, param):
        try:
            count_sql = f" SELECT count(`member_id`) FROM `view_member_weight` WHERE 1=1 %s"
            fetch_sql = f" SELECT `id`,`member_id`,`member_sno`,`weight_json`,`name`,`uname`,`sex`,`STATUS` " \
                        f" FROM `view_member_weight` WHERE 1=1 %s "
            where_sql = ""
            if len(param['key']) > 0:
                where_sql = where_sql + f" AND CONCAT(`member_id`,`uname`,`name`) like CONCAT('%',\'{param['key']}\','%') "
            int_begin = 0
            if int(param['pageNum']) > 1:
                int_begin = (int(param['pageNum']) - 1) * int(param['pageSize'])
            elif int(param['pageNum']) == 1:
                int_begin = 0 * int(param['pageSize'])
            where_sql_no_limit = where_sql
            where_sql_limit = where_sql_no_limit + f" LIMIT {int_begin}, {int(param['pageSize'])}"
            data_total = self.conn.sql_fetch(count_sql % where_sql_no_limit)
            data_list = self.conn.sql_fetch(fetch_sql % where_sql_limit)
            items = []
            if len(data_list) > 0:
                items = [MemberWieghtObj.load_db_2_dict(data=item) for item in data_list]
            return {"code": 200, "data": items, "total": data_total[0][0]}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": 500, "data": None}

    def fetch_one(self, member_id):
        fetch_sql = f" SELECT `id`,`member_id`,`member_sno`,`weight_json`,`name`,`uname`,`sex`,`STATUS`" \
                    f" FROM `view_member_weight` as `mem_member_weight` WHERE 1=1 " \
                    f" AND `member_id` = \'{member_id}\'"
        try:
            items = self.conn.sql_fetch(fetch_sql)
            if len(items) > 0:
                res = [MemberWieghtObj.load_db_2_dict(item) for item in items]
                return {"code": 200, "data": res}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def fetch_one_by_key(self, key):
        fetch_sql = f" SELECT `id`,`member_id`,`member_sno`,`weight_json`,`name`,`uname`,`sex`,`STATUS`" \
                    f" FROM `view_member_weight` as `mem_member_weight` WHERE 1=1 " \
                    f" AND CONCAT(`member_id`,`uname`,`name`) LIKE CONCAT( \"%\",\'{key}\', \"%\") "
        try:
            items = self.conn.sql_fetch(fetch_sql)
            if len(items) > 0:
                res = [MemberWieghtObj.load_db_2_dict(item) for item in items]
                return {"code": 200, "data": res}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def add_member_weight(self, member: object):
        try:
            add_check = self.count_one(member_id=member['member_id'])
            if add_check:
                return {"code": 203, "data": None}
            # print(json.dumps(member, sort_keys=True, ensure_ascii=False, indent=4))
            insert_sql = f" INSERT INTO `mem_member_weight` ({MemberWieghtObj.to_string(False)}) " \
                         " VALUES ( %s )" % MemberWieghtObj.concat_datas(member)
            self.conn.sql_commit(insert_sql)
            return {"code": 200, "data": None}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def update_member_weight(self, member, member_id):
        # 获取当前时间
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        try:
            add_check = self.count_one(member_id=member['member_id'])
            if not add_check:
                return {"code": 404, "data": None}
            old_member = self.fetch_one(member_id=member['member_id'])
            update_str = MemberWieghtObj.split_params(member)
            update_sql = f" UPDATE `mem_member_weight` SET %s, `UPDATE_DATE`=\'{current_time}\'" \
                         f" WHERE `MEMBER_ID`= \'%s\'" % (update_str, member_id)
            self.conn.sql_commit(update_sql)
            # 计算积分和会员等级
            acct_point = float(member['grow_value']) + old_member['data'][0]['acct_point']
            _mem_level_key = ""
            _mem_level = ""
            for point_level in MemberWieghtObj.MEM_POINT_LEVEL:
                if not float(point_level['max_points']) < acct_point:
                    _mem_level_key = point_level['key']
                    _mem_level = MemberWieghtObj.MEM_LEVEL[_mem_level_key]
                    break
            update_str = f"`ACCT_POINT`= {acct_point},`level`= '%s', `level_name`= '%s'" % (_mem_level_key, _mem_level)
            update_point_sql = f" UPDATE `mem_member_weight` SET %s WHERE `MEMBER_ID`= \'%s\'" % (update_str, member_id)
            self.conn.sql_commit(update_point_sql)
            if not _mem_level_key == member['level']:
                update_str = f"`UPGRADE_TIME`= \'{current_time}\'"
                update_level_sql = f" UPDATE `mem_member_weight` SET %s WHERE `MEMBER_ID`= \'%s\'" % (
                    update_str, member_id)
                self.conn.sql_commit(update_level_sql)
            return {"code": 200, "data": None}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def drop_member(self, member_id):
        # 获取当前时间
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        add_check = self.count_one(member_id=member_id)
        if not add_check:
            return {"code": 404, "data": None}
        execute_SQL = f" UPDATE `mem_member_weight` SET " \
                      f" `STATUS` = \'{MemberWieghtObj.MEM_STATUS['DROP']}\'," \
                      f" `UPDATE_DATE`=\'{current_time}\'" \
                      f" WHERE `MEMBER_ID` = \'{member_id}\'"
        self.conn.sql_commit(execute_SQL)
        return {"code": 200, "data": None}

    def res_member(self, member_id):
        # 获取当前时间
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        add_check = self.count_one(member_id=member_id)
        if not add_check:
            return {"code": 404, "data": None}
        execute_SQL = f" UPDATE `mem_member_weight` SET " \
                      f" `STATUS` = \'{MemberWieghtObj.MEM_STATUS['INUSE']}\'," \
                      f" `UPDATE_DATE`=\'{current_time}\'" \
                      f" WHERE `MEMBER_ID` = \'{member_id}\'"
        self.conn.sql_commit(execute_SQL)
        return {"code": 200, "data": None}

    def count_one(self, member_id) -> bool:
        fetch_sql = f"SELECT count(`MEMBER_ID`) FROM `mem_member_weight` WHERE 1 = 1 " \
                    f" AND `MEMBER_ID` = \'{member_id}\'"
        try:
            items = self.conn.sql_fetch(fetch_sql)
            if len(items) > 0:
                return items[0][0] > 0
            return False
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def fetch_member_inuse(self, param):
        try:
            where_sql = ""
            fetch_sql = f" SELECT `id`,`member_id`,`member_sno`,`weight_json`,`name`,`uname`,`sex`,`STATUS` " \
                        f" FROM `view_member_weight` WHERE 1=1 %s "
            if len(param["status"]) > 0:
                where_sql += f" AND `STATUS`= \'{param['status']}\'"
            if len(param["projects"]) > 0:
                fetch_project_sql = f" SELECT `id`,`name`,`camp_sno`,`mems_json` FROM `mem_projects` WHERE 1=1 AND `camp_sno` = \'%s\' " % \
                                    param["projects"]
                project_data_list = self.conn.sql_fetch(fetch_project_sql)
                if len(project_data_list) > 0:
                    mems_in_project = json.loads(project_data_list[0][3])
                    _str_rep = ",".join(["\'" + i + "\'" for i in mems_in_project])
                    where_sql += f" AND `member_id` in (%s) " % _str_rep
            if param["memID"] is not None and len(param["memID"]) > 0:
                where_sql += f" AND CONCAT(`member_id`,`name`,`uname`) LIKE CONCAT(\'%\',\'{param['memID']}\',\'%\')"
            order_sql = where_sql + f" ORDER BY `member_id` DESC"
            data_list = self.conn.sql_fetch(fetch_sql % order_sql)
            items = []
            if len(data_list) > 0:
                items = [MemberWieghtObj.load_db_2_dict(data=item) for item in data_list]
            return {"code": 200, "data": items}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": 500, "data": None}

    def cal_member_weight(self, view: object, memberId: str):
        if None is not memberId and len(memberId) > 0:
            res = self.fetch_one(member_id=memberId)
            if res["code"] != 200:
                return {'code': 99, 'data': None}
            view = res['data'][0]
        # 字典获取单份餐食总克重
        one_single_dinner_sample_kgs = 400
        cal_h = float(view['height']) / 100
        cal_w = float(view['weight'])
        # （BMI）=体重（kg）÷身高^2（m）
        BMI = round((cal_w / (cal_h * cal_h)), 2)
        # 基础计算数据 男性系数 / 女性系数
        # 静态系数.staticCoefficient = 20;
        # 动态系数.dynamicCoefficient = 3 / 100;
        # 静态系数.staticCoefficient = 18;
        # 动态系数.dynamicCoefficient = 2 / 100;
        # 成年女性体脂率一般要求在20%-25%之间，男性患者要求在15%-18%左右
        if int(view['sex']) == 0:
            # 成年男性体脂率的计算公式：参数A=腰围（cm）×0.74，参数B=体重（kg）×0.082+44.74，体脂肪重量（kg）=A-B，体脂率=身体脂肪总重量÷体重×100%。
            # 男性系数
            staticCoefficient = 20
            # 体脂率 = 1.2*BMI+0.23*年龄-16.2
            FAT = 1.2 * BMI + 0.23 * int(view['age']) - 16.2
        else:
            # 成年女性体脂率的计算公式：参数A=腰围（cm）×0.74，参数B=体重（kg）×0.082+34.89。体脂肪重量（kg）=A-B，体脂率=身体脂肪总重量÷体重×100%。
            # 女性系数
            staticCoefficient = 18
            # 体脂率 = 1.2*BMI+0.23*年龄-5.4
            FAT = 1.2 * BMI + 0.23 * int(view['age']) - 5.4
        dynamicCoefficient = 20 / 100
        # 调整计算公式
        # 总消耗（打卡 / 焦）动态消耗值 + 静态消耗值
        # 动态消耗值 = 静态消耗值 * 动态系数
        # 静态消耗值 = 静态系数 * 体重
        loss_A = float(view['weight']) * staticCoefficient
        loss_B = loss_A * dynamicCoefficient
        bodyFatRat = round(FAT, 2)
        calories_std = loss_A + loss_B
        # TODO 2024-03-16 1-1 会员注册时候加入体质计算数据
        view["bmi"] = BMI
        calor_gap = MemberWieghtObj.cal_member_heat_gap(view)
        # 会员体质热量 - 热量缺口 = 计算餐食热量
        cal_calor_gap = calories_std - calor_gap
        # 蛋白质系数是4，计算公式（举例：某人体重在150斤*4=600大卡）
        proteinFactor = 4
        proteinStd = (2 * cal_w) * proteinFactor
        proteinWeight = (2 * cal_w) * 1
        proteinWeight = round(proteinWeight, 0)
        # 脂肪系数是15%，9，计算公式（举例： 体重在150斤，每日需要摄入1500大卡热量，1500大卡*0.15=225大卡÷9=25g）
        cal_fatCoefficient = 15
        fatCoefficient = round(cal_fatCoefficient / 100, 2)
        fatStd = round((cal_calor_gap * fatCoefficient), 2)
        fatWeight = fatStd / 9
        fatWeight = round(fatWeight, 0)
        # 碳水化合物系数是4，公式<举例：某人体重在150斤，每日需要摄入1500大卡热量，1500大卡（总热量）-225大卡（脂肪大卡）-600大卡（蛋白质大卡）=675大卡（每日所摄入的大卡） 675大卡÷4=168g
        carbonWaterCoefficient = 4
        carbonWaterStd = round((cal_calor_gap - fatStd - proteinStd), 2)
        carbonWaterWeight = carbonWaterStd / 4
        carbonWaterWeight = round(carbonWaterWeight, 0)
        # ------------------------------------------------------------------------- 2024-03027删除，改用数据字典中男女餐食标准克重计算 START
        vitaminCoefficient = 0
        vitaminCoefficient = float(vitaminCoefficient)
        # 维他命克重为上述数据总重量的15%作为补充
        vitaminStd = round(cal_calor_gap * round(vitaminCoefficient / 100, 2), 2)  # 这里计算维生素的热量 2024-03-22
        # vitaminWeight = (carbonWaterWeight + proteinWeight + fatWeight) * 0.15 # 维生素占有计算餐值克重的15% 2024-03-22
        # fuck = (carbonWaterWeight + proteinWeight + fatWeight)
        # if one_single_dinner_sample_kgs > fuck:
        #     vitaminWeight = (fuck * (vitaminCoefficient / 100))  # 维生素占有计算餐值克重的15% 2024-03-22
        # else:
        #     vitaminWeight = one_single_dinner_sample_kgs - fuck  # 维生素占有计算餐值克重的15% 2024-03-22
        # if int(view['sex']) == 0:
        #     dinner_std_weight = _dict.load_dict_val(key_eng="mDinnerStdKgs")["data"]["val"]
        # elif int(view['sex']) == 1:
        #     dinner_std_weight = _dict.load_dict_val(key_eng="fDinnerStdKgs")["data"]["val"]
        # # 数据总热量 - 计算热量 = 剩余维生素配菜热量
        # _tmp_cal_dinner_tot_weight = float(fatWeight) + float(carbonWaterWeight) + float(proteinWeight)
        # # 2024-03-27 需求补充, 餐食克重 > 热量餐食克重，正常计算.标准克重 - 热量克重 = 配菜克重
        # if float(dinner_std_weight) > _tmp_cal_dinner_tot_weight:
        #     cal_vitamin = float(dinner_std_weight) - _tmp_cal_dinner_tot_weight
        # elif _tmp_cal_dinner_tot_weight > float(dinner_std_weight):
        #     # 热量餐食克重 > 餐食克重, 补充餐食克重的维生素比重
        #     cal_vitamin = float(dinner_std_weight) * round(vitaminCoefficient / 100, 2)
        # else:
        #     cal_vitamin = round((float(fatWeight) + float(carbonWaterWeight) + float(proteinWeight)) * round(vitaminCoefficient / 100, 2), 2)
        vitaminWeight = round(vitaminStd, 0)
        # ------------------------------------------------------------------------- 2024-03027删除，改用数据字典中男女餐食标准克重计算 END
        view_obj = {
            "name": str(view['name']),
            "age": int(view['age']),
            "sex": int(view['sex']),
            "weight": float(view['weight']),
            "height": float(view['height']),
            "BMI": BMI,
            "bodyFatRat": bodyFatRat,  # 体脂率
            "calories": round(calories_std, 3),  # 体质总热量
            "calorGap": calor_gap,
            "calCalorGap": cal_calor_gap,
            "loss_A": round(loss_A, 3),  # 静态值
            "loss_B": round(loss_B, 3),  # 动态值
            "staticCoefficient": staticCoefficient,  # 生物静态系数
            "dynamicCoefficient": dynamicCoefficient,  # 生物动态系数
            "proteinFactor": proteinFactor,  # 蛋白质系数
            "proteinStd": proteinStd,  # 蛋白质指标
            "proteinWeight": proteinWeight,
            "fatCoefficient": fatCoefficient,  # 脂肪系数
            "fatStd": fatStd,  # 脂肪指标
            "fatWeight": float(round(fatWeight, 2)),
            "carbonWaterCoefficient": carbonWaterCoefficient,  # 碳水化合物系数
            "carbonWaterStd": carbonWaterStd,  # 碳水指标
            "carbonWaterWeight": carbonWaterWeight,
            "vitaminCoefficient": vitaminCoefficient,  # 维生素指标
            "vitaminStd": vitaminStd,  # 维生素指标
            "vitaminWeight": vitaminWeight
        }
        MyLogs.logger.info("=" * 100 + "会员体质信息" + "START")
        MyLogs.logger.info("# 姓名: name" + ("-" * 5) + "数据来源：系统采集" + (" -" * 15) + str(view['name']))
        MyLogs.logger.info("# 年龄: age" + "-" * 5 + "数据来源：系统采集" + (" -" * 15) + str(view['age']))
        MyLogs.logger.info("# 性别: sex" + "-" * 5 + "数据来源：系统采集" + (" -" * 15) + str(view['sex']))
        MyLogs.logger.info("# 体重: weight" + "-" * 5 + "数据来源：系统采集" + (" -" * 15) + str(view['weight']))
        MyLogs.logger.info("# 身高: height" + "-" * 5 + "数据来源：系统采集" + (" -" * 15) + str(view['height']))
        MyLogs.logger.info("# BMI: BMI" + "-" * 5 + "数据来源：（BMI）=体重（kg）÷身高^2（m）" + (" -" * 15) + str(BMI))
        MyLogs.logger.info(
            "# 体脂率: bodyFatRat" + "-" * 5 + "数据来源：1.2*BMI+0.23*年龄-16.2" + (" -" * 15) + str(bodyFatRat))
        MyLogs.logger.info(
            "# 生物静态系数: staticCoefficient" + "-" * 5 + "数据来源：系统参数，默认男性20，女性18" + (" -" * 15) + str(
                staticCoefficient))
        MyLogs.logger.info(
            "# 生物动态系数: dynamicCoefficient" + "-" * 5 + "数据来源：系统参数，默认0.2" + (" -" * 15) + str(
                dynamicCoefficient))
        MyLogs.logger.info(
            "# 静态值: loss_A" + "-" * 5 + "数据来源：静态系数 * 体重" + (" -" * 15) + str(round(loss_A, 3)))
        MyLogs.logger.info(
            "# 动态值: loss_B" + "-" * 5 + "数据来源：静态消耗值 * 动态系数" + (" -" * 15) + str(round(loss_B, 3)))
        MyLogs.logger.info(
            "# 体质总热量: calories" + "-" * 5 + "数据来源：总消耗（打卡 / 焦）= 动态消耗值 + 静态消耗值" + (
                        " -" * 15) + str(round(calories_std, 3)))
        MyLogs.logger.info("# 热量缺口: calorGap" + "-" * 5 + "数据来源：系统参数" + (" -" * 15) + str(calor_gap))
        MyLogs.logger.info(
            "# 计算热量:  calCalorGap" + "-" * 5 + "数据来源：系统采集" + (" -" * 15) + str(cal_calor_gap))
        MyLogs.logger.info(
            "# 蛋白质系数: proteinFactor" + "-" * 5 + "数据来源：系统参数，默认4" + (" -" * 15) + str(proteinFactor))
        MyLogs.logger.info(
            "# 蛋白质指标: proteinStd" + "-" * 5 + "数据来源：系统计算，体重（斤）* 4" + (" -" * 15) + str(proteinStd))
        MyLogs.logger.info(
            "# 蛋白质摄入克重: proteinWeight" + "-" * 5 + "数据来源：系统计算，体重（斤）* 1" + (" -" * 15) + str(
                proteinWeight))
        MyLogs.logger.info(
            "# 脂肪系数: fatCoefficient" + "-" * 5 + "数据来源：系统参数，默认15" + (" -" * 15) + str(fatCoefficient))
        MyLogs.logger.info(
            "# 脂肪指标: fatStd" + "-" * 5 + "数据来源：系统计算，热量缺口 * 脂肪系数" + (" -" * 15) + str(fatStd))
        MyLogs.logger.info(
            "# 脂肪摄入克重: fatWeight" + "-" * 5 + "数据来源：系统计算，热量缺口 * 脂肪系数 / 9 " + (" -" * 15) + str(
                round(fatWeight, 2)))
        MyLogs.logger.info(
            "# 碳水化合物系数: carbonWaterCoefficient" + "-" * 5 + "数据来源：系统参数，默认4" + (" -" * 15) + str(
                carbonWaterCoefficient))
        MyLogs.logger.info("# 碳水指标: carbonWaterStd" + "-" * 5 + "数据来源：系统计算，(总热量-脂肪大卡-蛋白质大卡)" + (
                    " -" * 15) + str(carbonWaterStd))
        MyLogs.logger.info(
            "# 碳水摄入克重: carbonWaterWeight" + "-" * 5 + "数据来源：系统计算，(总热量-脂肪大卡-蛋白质大卡)÷碳水化合物系数" + (
                        " -" * 15) + str(carbonWaterWeight))
        MyLogs.logger.info("# 维生素系数: vitaminCoefficient" + "-" * 5 + "数据来源：系统参数，默认0" + (" -" * 15) + str(
            vitaminCoefficient))
        MyLogs.logger.info(
            "# 维生素指标: vitaminStd" + "-" * 5 + "数据来源：系统参数，默认0" + (" -" * 15) + str(vitaminStd))
        MyLogs.logger.info(
            "# 维生素摄入克重: vitaminWeight" + "-" * 5 + "数据来源：系统参数，默认0" + (" -" * 15) + str(vitaminWeight))
        MyLogs.logger.info("=" * 40 + "会员体质信息" + "END")
        return {'code': 200, 'data': view_obj, 'message': ""}

    # 通过界面调整变更会员的热量缺口数值，该数值用于热量分析计算用。
    # TODO 2024-03-16 1-1 会员注册时候加入体质计算数据
    def set_mem_heatGap_json(self, member_id, heatgap):
        # 获取当前时间
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        fetch_sql = f" SELECT `id`, `member_id`, `weight_json`" \
                    f" FROM `mem_member_weight` WHERE 1=1 " \
                    f" AND `member_id` = \'{member_id}\'"
        try:
            items = self.conn.sql_fetch(fetch_sql)
            if len(items) > 0:
                one_data = [{"id": item[0], "member_id": item[1], "weight_json": item[2]} for item in items][0]
                str_weight_json = one_data["weight_json"]
                obj_weight_json = json.loads(str_weight_json)
                obj_weight_json["heatgap"] = int(heatgap)
                one_data["weight_json"] = json.dumps(obj_weight_json, ensure_ascii=False)
                update_str = MemberWieghtObj.split_params(one_data)
                update_sql = f" UPDATE `mem_member_weight` SET %s" \
                             f" WHERE `MEMBER_ID`= \'%s\'" % (update_str, member_id)
                self.conn.sql_commit(update_sql)
                return {'code': 200, 'data': one_data, 'message': ""}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def set_mem_weight_json(self, member_id, data):
        # 获取当前时间
        # current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        try:
            view_data = self.fetch_one(member_id=member_id)["data"][0]
            fetch_sql = f" SELECT `id`, `member_id`, `weight_json` FROM `mem_member_weight` WHERE 1=1 AND `member_id` = \'{member_id}\'"
            mem_weight_items = self.conn.sql_fetch(fetch_sql)
            if len(mem_weight_items) > 0:
                mem_weight = \
                    [{"id": item[0], "member_id": item[1], "weight_json": item[2]} for item in mem_weight_items][0]
                # # STEP 1 更新基础数据 DROP
                str_weight_json = mem_weight["weight_json"]
                obj_weight_json = json.loads(str_weight_json)
                obj_weight_json["height"] = float(data["height"])
                obj_weight_json["weight"] = float(data["weight"])
                obj_weight_json["age"] = int(data["age"])
                mem_weight["weight_json"] = json.dumps(obj_weight_json, ensure_ascii=False)
                # STEP 1.2 加入一次数据计算, 使用页面输入的数据计算BMI和热量缺口
                cal_bmi = float(data["weight"]) / (float(data["height"]) / 100 * float(data["height"]) / 100)
                cal_view = {"name": str(view_data['name']),
                            "age": int(data["age"]),
                            "sex": int(view_data['sex']),
                            "BMI": float(cal_bmi),
                            "weight": float(data["weight"]),
                            "height": float(data["height"])}
                caled_data = self.cal_member_weight(view=cal_view, memberId=None)
                # STEP 2 重新配置计算后的数据值
                str_weight_json = mem_weight["weight_json"]
                obj_weight_json = json.loads(str_weight_json)
                obj_weight_json["height"] = float(data["height"])
                obj_weight_json["weight"] = float(data["weight"])
                obj_weight_json["age"] = int(data["age"])
                check_heatgap = 0
                try:
                    check_heatgap = float(data["heatgap"])
                except KeyError as kerry:
                    check_heatgap = obj_weight_json["heatgap"]
                check_bmi = 0
                try:
                    check_bmi = float(data["bmi"])
                except KeyError as kerry:
                    check_bmi = float(caled_data["data"]["BMI"])
                check_bodyFatRat = 0
                try:
                    check_bodyFatRat = float(data["bodyFatRat"])
                except KeyError as kerry:
                    check_bodyFatRat = float(caled_data["data"]["bodyFatRat"])

                obj_weight_json["heatgap"] = check_heatgap
                obj_weight_json["bmi"] = check_bmi
                obj_weight_json["bodyFatRat"] = check_bodyFatRat
                mem_weight["weight_json"] = json.dumps(obj_weight_json, ensure_ascii=False)
                update_str = MemberWieghtObj.split_params(mem_weight)
                update_sql = f" UPDATE `mem_member_weight` SET %s" \
                             f" WHERE `MEMBER_ID`= \'%s\'" % (update_str, member_id)
                self.conn.sql_commit(update_sql)
                # STEP 3加入计算历史数据
                # 记录历史数据
                mem_weight["height"] = float(data["height"])
                mem_weight["weight"] = float(data["weight"])
                mem_weight["age"] = int(data["age"])
                mem_weight["bmi"] = check_bmi
                mem_weight["bodyFatRat"] = check_bodyFatRat
                mem_weight["heatgap"] = check_heatgap
                self.add_cal_heat_gap_his(member=mem_weight)
                return {'code': 200, 'data': mem_weight, 'message': ""}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def add_cal_heat_gap_his(self, member: object):
        # 获取当前时间
        # current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        cal_day = datetime.now().strftime("%Y-%m-%d")
        try:
            # 数据处理
            # 更新当天的记录，而不插入新记录
            fetch_sql = f" SELECT count(id) " \
                        f" FROM `mem_member_weight_rrk` " \
                        f" WHERE 1=1 AND `member_id` = \'{member['member_id']}\' " \
                        f" AND DATE_FORMAT(`cal_date`,'%Y-%m-%d') = \'{cal_day}\'"
            chk_data = MemberWieghtObj.pruTuut_conn.sql_execute(fetch_sql)
            if len(chk_data) > 0 and chk_data[0][0] > 0:
                # 更新记录
                update_str = MemberWieghtObj.split_params(member)
                update_sql = f" UPDATE `mem_member_weight_rrk` set %s WHERE `id` = %s" % (
                update_str, str(chk_data[0][1]))
                MemberWieghtObj.pruTuut_conn.sql_commit(update_sql)
                return {"code": 200, "data": None}

            # 计算数据数量
            fetch_sql = f" SELECT id " \
                        f" FROM `mem_member_weight_rrk` " \
                        f" WHERE 1=1 AND `member_id` = \'{member['member_id']}\' " \
                        f" ORDER BY cal_date ASC "
            rrks_data = MemberWieghtObj.pruTuut_conn.sql_execute(fetch_sql)
            if len(rrks_data) > 0:
                # 删除一条旧数据，保留7条数据
                rrks_fst_id = rrks_data[0][0]
                if len(rrks_data) == 7:
                    # 删除最早的数据
                    update_sql = f" DELETE FROM `mem_member_weight_rrk` " \
                                 f" WHERE `member_id`= \'%s\' AND id = %d" % (member['member_id'], rrks_fst_id)
                    MemberWieghtObj.pruTuut_conn.sql_commit(update_sql)
            # 添加记录
            _str_cols = "`cal_date`" + ", " + MemberWieghtObj.to_string(False)
            _str_datas = "'" + cal_day + "'" + ", " + MemberWieghtObj.concat_datas(member)
            insert_sql = f" INSERT INTO `mem_member_weight_rrk` ( %s ) VALUES ( %s )" % (_str_cols, _str_datas)
            MemberWieghtObj.pruTuut_conn.sql_commit(insert_sql)
            return {"code": 200, "data": None}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def fetchWeightHis(self, member_id):
        try:
            fetch_sql = f" SELECT `id`,`cal_date`,`member_id`,`weight_json`, `NAME` " \
                        f" FROM `view_member_weight_rrk` WHERE 1=1 %s "
            where_sql = f" AND `member_id`= \'{member_id}\'"
            order_sql = where_sql + f" ORDER BY `cal_date` ASC"
            data_list = self.conn.sql_fetch(fetch_sql % order_sql)
            items = []
            if len(data_list) > 0:
                items = [{"id": item[0], "cal_date": str(item[1]),
                          "member_id": str(item[2]), "weight_json": item[3], "name": item[4]}
                         for item in data_list]
            # 将日期并入到weight_json对象中
            for item in items:
                if item["cal_date"] == 'None':
                    continue
                weight_obj = json.loads(item["weight_json"])
                weight_obj["cal_date"] = datetime.strptime(item["cal_date"], "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d")
                _cal_tmp = float(float(weight_obj["weight"]) / (
                            (float(weight_obj["height"]) / 100) * (float(weight_obj["height"]) / 100)))
                weight_obj["bmi"] = round(_cal_tmp, 2)
                item["weight_json"] = json.dumps(weight_obj, ensure_ascii=False)
            return {"code": 200, "data": items}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": 500, "data": None}

    # 读取到用户的上一个数据，写入到历史记录表
    def uploadMemWeightWithFile(self, rows):
        try:
            for row in rows:
                if row['name'] is not None and row['height'] is not None and row['weight'] is not None:
                    mem_res = self.fetch_one_by_key(row['name'])
                    if mem_res["code"] == 200:
                        mem_obj = mem_res["data"][0]
                        self.set_mem_weight_json(mem_obj["member_id"], row)
            return {"code": 200, "data": None}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": 500, "data": None}
